import type { AppIdsMap, AppNodeCharacter, AuthNode, AuthTree, TreeNodeCharacter, TreeSelectorRefs } from '@/types/RoleAuthorization';
import { ref } from 'vue';
import { Authorized } from '@/constants/RoleAuthorization';

// 树数据处理
export function useTreeData() {
  const treeData = ref<AuthTree>([]);
  const appCodeArray = ref<AppIdsMap>({});
  const treeAddSelect = ref<string[]>([]);
  const functionalResult = ref<{ authorized0: TreeNodeCharacter[], authorized1: TreeNodeCharacter[] }>({
    authorized0: [],
    authorized1: [],
  });
  const treeSelectorRefs = ref<TreeSelectorRefs>({});
  const activePermissionTab = ref('function');
  // 递归收集所有 ID
  const collectAllIds = (nodes: any): number[] => {
    const ids: number[] = [];
    const traverse = (node: any): void => {
      if (node.id !== undefined) {
        ids.push(node.id);
      }
      if (node.children?.length) {
        node.children.forEach((child: AuthNode) => traverse(child));
      }
    };

    nodes.forEach((node: AuthTree) => traverse(node));
    return ids;
  };

  // 处理返回来的数据{父节点id:[]}
  const processAppData = (data: AuthTree): AppIdsMap => {
    if (!Array.isArray(data)) {
      console.warn('processAppData: data is not an array', data);
      return {};
    }
    return data.reduce((acc: AppIdsMap, app) => {
      acc[app.id!] = collectAllIds(app.children || []);
      return acc;
    }, {});
  };

  // 分成授权和未授权两个数组,加上appId:(根节点的id)
  const groupByAuthorizedFunctional = (data: AppNodeCharacter[]): {
    authorized0: TreeNodeCharacter[]
    authorized1: TreeNodeCharacter[]
  } => {
    treeAddSelect.value = [];
    const allNodes: TreeNodeCharacter[] = [];
    const authorized1LeafNodes: TreeNodeCharacter[] = [];
    const traverseWithAppId = (nodes: TreeNodeCharacter[], appId: string) => {
      nodes.forEach((node) => {
        const isLeafNode = !node.children || node.children.length === 0;
        if (node.authorized === Authorized.WITH_PERMISSION) {
          treeAddSelect.value.push(String(node.id));
          if (isLeafNode) {
            authorized1LeafNodes.push({
              ...node,
              appId,
            });
          }
        }
        allNodes.push({
          ...node,
          appId,
        });

        if (node.children && node.children.length > 0) {
          node.children.forEach((child: TreeNodeCharacter) => traverseWithAppId([child], appId));
        }
      });
    };

    data.forEach(app => traverseWithAppId(app.children, String(app.id)));
    const currentRef = treeSelectorRefs.value[activePermissionTab.value];
    if (currentRef?.setCheckedKeys) {
      try {
        currentRef?.setCheckedKeys(treeAddSelect.value);
      } catch (error) {
        console.error('调用子组件方法失败:', error);
      }
    } else {
      console.warn('treeSelectorRef 方法不可用，跳过获取选中数据');
    }
    return {
      authorized0: allNodes.filter(node => node.authorized === Authorized.NO_PERMISSION),
      authorized1: authorized1LeafNodes, // 只返回叶子节点且 authorized === 1
    };
  };

  // 设置树数据
  const setTreeData = (data: AuthTree) => {
    treeData.value = data;
    appCodeArray.value = processAppData(data);
    functionalResult.value = groupByAuthorizedFunctional(data as AppNodeCharacter[]);
  };

  return {
    treeData,
    appCodeArray,
    functionalResult,
    treeAddSelect,
    treeSelectorRefs,
    activePermissionTab,
    setTreeData,
    processAppData,
    groupByAuthorizedFunctional,
  };
}
